package listener;

import pojo.Product;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.HashMap;
import java.util.Map;

@WebListener
public class ContextListener implements ServletContextListener, ServletContextAttributeListener {


        @Override
        public void contextInitialized(ServletContextEvent sce) {
            //1.1 定义一组商品
            Product p1 = new Product("1","手机",888,10);
            Product p2 = new Product("2","电脑",22222,12);
            Product p3 = new Product("3","空调",3333,123);
            Product p4 = new Product("4","电视",444,321);
            Product p5 = new Product("5","冰箱",5555,123);
            Product p6 = new Product("6","彩电",666,321);
            Product p7 = new Product("7","摩托车",777,312);
            Product p8 = new Product("8","电动车",88,213);
            Product p9 = new Product("9","玉嫂",999,132);
            Product p10 = new Product("10","飞机",888888777,321);
            //put进集合
            Map<String,Product> productMap = new HashMap<>();
            productMap.put(p1.getPid(),p1);
            productMap.put(p2.getPid(),p2);
            productMap.put(p3.getPid(),p3);
            productMap.put(p4.getPid(),p4);
            productMap.put(p5.getPid(),p5);
            productMap.put(p6.getPid(),p6);
            productMap.put(p7.getPid(),p7);
            productMap.put(p8.getPid(),p8);
            productMap.put(p9.getPid(),p9);
            productMap.put(p10.getPid(),p10);
            //set到区域
            sce.getServletContext().setAttribute("products",productMap);
        }

        @Override
        public void contextDestroyed(ServletContextEvent sce) {
            System.out.println("上下文被销毁。。。");
        }
        //2. application组件属性值改变的监听
        @Override
        public void attributeAdded(ServletContextAttributeEvent event) {
            System.out.println("上下文属性已填加");
        }

        @Override
        public void attributeRemoved(ServletContextAttributeEvent event) {
            System.out.println("上下文属性已删除");
        }

        @Override
        public void attributeReplaced(ServletContextAttributeEvent event) {

        }


}
